package edu.jmu.action.user;


import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;

import edu.jmu.action.BaseAction;
import edu.jmu.bean.system.LoginLog;
import edu.jmu.bean.user.User;
import edu.jmu.service.sysmanage.LoginLogService;
import edu.jmu.service.user.UserService;
import edu.jmu.utils.WebUtil;
@Controller
@Namespace("/user")
@Scope(value="prototype")
public class LoginUserAction extends BaseAction<User> {
	private static final long serialVersionUID = -2398580087478628434L;
	@Resource
	private UserService userService;
	@Resource
	private LoginLogService loginLogService;
	private User user;
	private String validationCode;
	
	@Validations(requiredStrings={
			@RequiredStringValidator(fieldName="user.userName",message="请输入用户名"),
			@RequiredStringValidator(fieldName="user.passWord",message="请输入密码"),
			@RequiredStringValidator(fieldName="validationCode",message="请输入验证码")
	})
	@Action(value="userLogin",results={
			@Result(location="/default.jsp",type="redirect"),
			@Result(name=INPUT,location="/index.jsp",params={
					"message","${message}"
			})
	})
	public String userLogin() throws Exception{
		LoginLog loginLog = new LoginLog();		
		loginLog.setLoginUserIp(ServletActionContext.getRequest().getRemoteAddr());
		loginLog.setUser(user);
		if(!WebUtil.getValidationCode().equals(validationCode.trim())){
			message = "验证码错误";		
			return INPUT;
		}else if(!userService.checkUser(user)){	
			message = "帐户或密码错误";
			loginLog.setLoginDesc("登陆失败");
			loginLog.setSuccess(false);
			loginLogService.save(loginLog);
			return INPUT;
		}else{
			loginLog.setLoginDesc("登陆成功");
			loginLog.setSuccess(true);
			loginLogService.save(loginLog);
			WebUtil.setUser(userService.find(user.getUserName()));			
			return SUCCESS;			
		}
			
	}

	
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
	public String getValidationCode() {
		return validationCode;
	}
	public void setValidationCode(String validationCode) {
		this.validationCode = validationCode;
	}
	
	
}
